﻿using Infrastructure.Crosscutting.Loggers;
using System.Linq;
using System;

namespace Infrastructure.Data.Uow.Log
{
    public static class LoggerRepositoryManager
    {
        #region Members

        static ILoggerReopsitoryFactory logRepositoryFactory = new LoggerRepositoryFactory();

        #endregion

        static LoggerRepositoryManager()
        {
            //logRepositoryFactory = 
        }

        #region Public Methods

        public static void SetCurrentLoggerFactory(ILoggerReopsitoryFactory logFactory)
        {
            logRepositoryFactory = logFactory;
        }

        public static ILoggerReopsitory CreateLogger()
        {
            return (logRepositoryFactory != null) ? logRepositoryFactory.CreateLogger() : null;
        }

        public static void AddLogInfo(string message)
        {
            System.IO.StreamWriter sw = null;
            try
            {
                var logPath = System.IO.Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "log.txt");
                sw = new System.IO.StreamWriter(logPath, true);
                sw.WriteLine(message);
                sw.Close();
                sw.Dispose();
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                }
            }
        }

        public static void AddLogInfo(int logType, int userId, string pageUrl, string refUrl, string shortMessage, string fullMessage, string ipAddress)
        {
            var logRepository = CreateLogger();
            if (logRepository != null)
            {
                Domain.Entity.Log logModel = new Domain.Entity.Log();
                logModel.AddTime = System.DateTime.Now;
                logModel.FullMessage = fullMessage;
                logModel.IpAddress = ipAddress;
                logModel.PageUrl = pageUrl;
                logModel.ReferrerUrl = refUrl;
                logModel.ShortMessage = shortMessage;
                logModel.State = true;
                logModel.TypeId = logType;
                logModel.UserId = userId;
                logRepository.Add(logModel);
                logRepository.Uow.Commit();
            }
        }

        public static void AddLogInfo(Domain.Entity.Log log)
        {
            var logRepository = CreateLogger();
            if (logRepository != null)
            {
                logRepository.Add(log);
                try
                {
                    logRepository.Uow.Commit();
                }
                catch (System.Exception ex)
                { }
            }
        }

        #endregion
    }
}
